import axios from "axios";
import { type OpenAI } from "openai";
import { type FunctionParameters } from "openai/resources/shared.mjs";
import { type OpenAPIObject } from "openapi3-ts/oas30";
import MarkdownIt from "markdown-it";
import { resolve } from "url";
const md = new MarkdownIt();
function getApiList(apiList: OpenAPIObject) {
  let tools: OpenAI.Chat.Completions.ChatCompletionTool[] = [];

  for (const path in apiList.paths) {
    //   console.log(apiList.components.schemas[path.slice(1) + '_form_model']);

    let Parameters: FunctionParameters | undefined;
    if (
      apiList.components &&
      apiList.components.schemas &&
      apiList.components.schemas[path.slice(1) + "_form_model"]
    ) {
      // console.log(apiList.components.schemas[path.slice(1) + "_form_model"]);

      Parameters = {
        type: apiList.components.schemas[path.slice(1) + "_form_model"]["type"],

        properties:
          apiList.components.schemas[path.slice(1) + "_form_model"][
            "properties"
          ],

        required:
          apiList.components.schemas[path.slice(1) + "_form_model"][
            "required"
          ] || [],
      };
    }

    const tool: OpenAI.Chat.Completions.ChatCompletionTool = {
      type: "function",

      function: {
        name:
          (apiList.servers ? apiList.servers[0].url.slice(1) + "." : "") +
          path.slice(1),
        description:
          apiList.paths[path].post && apiList.paths[path].post.description,
        parameters: Parameters,
      },
    };
    tools.push(tool);
  }

  return tools;
}

async function getToolList(baseUrl: string) {
  axios.defaults.baseURL = baseUrl;
  const toolList: OpenAI.Chat.Completions.ChatCompletionTool[] = [];
  const apiList = await axios.get("/openapi.json").then((res) => res.data);

  //   console.log(apiList);
  if (Object.keys(apiList.paths).length === 0 && apiList.info.description) {
    const api = md.render(apiList.info.description);
    // console.log(api);
    //   获取链接
    const links = api.match(/href="(.*?)"/g);
    if (links) {
      for await (const item of links) {
        const link = item.match(/href="(.*?)"/);
        // console.log(link);
        if (link && link[1]) {
          const url = resolve(link[1], "openapi.json");

          await axios.get(url).then((res) => {
            // console.log(res.data);
            const tools = getApiList(res.data);
            //   console.log(tools);
            toolList.push(...tools);
          });
        }
      }
    }
  } else {
    const tools = getApiList(apiList);
    toolList.push(...tools);
  }

  //   console.log(toolList);

  return toolList;
}

export default getToolList;
